package com.bridgeintelligent.tag.webserver.security.session;

import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.ShiroHttpServletResponse;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class UserSessionFilter extends AdviceFilter {

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        ShiroHttpServletRequest servletRequest = (ShiroHttpServletRequest) request;
        // String allowOrigins = "http://10.199.60.74:17202,http://10.200.123.113.30001,http://115.29.66.164:30001,http://localhost:8081";
        String allowOrigins = "*";
        String requestURL = servletRequest.getRequestURL().toString();
        // 过滤静态资源
        if (!requestURL.contains("/api") || requestURL.contains("/static") ||
                requestURL.contains("/index") || requestURL.contains("login")) {
            return true;
        }
        HttpSession session = servletRequest.getSession();
        String id = session.getId();
        User currentUser = (User) session.getAttribute(TagConstants.SESSION_KEY_OF_USER);
        if (currentUser != null) {
            if (requestURL.contains("/api") && (requestURL.contains("engine") || requestURL.contains("batch")
                    || requestURL.contains("security") || requestURL.contains("query/customerDetail")
                    || requestURL.contains("provider") || requestURL.contains("user/synch"))) {
                return true;
            }
            if (id.equals(UserSessionManager.newInstance().getSession(currentUser.getUserId()))) {
                return true;
            }
        }
        // 重定向到登录
        log.warn("SessionNotEquals,Redirect...");
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        servletResponse.addHeader("logout", "ForcedReturn");
        servletResponse.setHeader("Access-Control-Allow-Origin", allowOrigins);
        servletResponse.setStatus(401);
        servletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        return false;
    }
}
